<template>
  <div class="imgItem"  style="cursor: pointer;" :style="{width:w,height:h}">
    <!--    -->
    <!--<img src="../../../assets/old/home/icon49.png" />-->
    <!--    <input type="file" @change="multipleChange($event)" accept="*" multiple="multiple" v-if="multiple == 'multiple'">-->
    <!--    <input type="file" @change="change($event)" accept="*" v-else>-->



<!--    ref="uploadImg"-->
<!--    class="upload-demo"-->
<!--    :action="url"-->
<!--    :headers="headers"-->
<!--    :before-upload="imgBeforeUpload"-->
<!--    :on-preview="handlePreview"-->
<!--    :on-remove="handleRemove"-->
<!--    :on-success="handleImageSuccess"-->
<!--    multiple-->
<!--    list-type="picture"-->
<!--    :limit="6"-->
<!--    :on-exceed="handleExceed"-->
<!--    :file-list="fileList"-->
    <el-upload
      ref="uploadImg"
      class="upload-demo"
      :action="url"
      :headers="headers"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleImageSuccess"
   >
      <el-button size="small" type="primary">点击上传图片</el-button>
      <div slot="tip" class="el-upload__tip">只能上传图片格式文件</div>
    </el-upload>

  </div>
</template>



<script type="text/ecmascript-6">
  // import { client } from '../../../Plugin/oss/index'
  //const OSS = require('ali-oss')
  // import { QingStor, Config, version } from 'qingstor-sdk/dist/qingstor-sdk-browser';
  import { getToken } from '@/utils/auth'

  export default {
    props: {
      //宽
      w: {
        type: [String, Number]
      },
      //高
      h: {
        type: [String, Number]
      },
      formDataId: {
        type: [String, Number]
      },
      multiple:{
        type: [String, Number],
        default:'single'
      }
    },
    directives: {},
    components: {},
    data() {
      return {
        //上传文件列表
        fileList:[],
        // // //上传图片headers
        headers:{
          'Authorization': null
        },
        url:'',
        a: "",
        imageUrl: '',
        name:'test'
      };
    },
    mounted(){
      //console.log(client)
      console.log(this.multiple)
      this.getUrl()
    },
    methods: {
      getUrl(){
        console.log("接口前缀", process.env.VUE_APP_BASE_API)
        //******************************************************************************
        let url =   process.env.VUE_APP_BASE_API+'/common/upload/'
        // let videoUrl =   process.env.VUE_APP_BASE_API+'/common/uploadVideo'
        //192.168.0.100:8082/manage/common/uploadVideo
        this.url = url
        // 图片上传
        // this.videoUrl = videoUrl
        // this.apiUrl = url
        console.log("整体图片接口",url)
        // console.log("整体视频接口",videoUrl)
        this.headers.Authorization ='Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
        // this.videoHeaders.Authorization ='Bearer ' + getToken()
      },

      //上传图片************************************************************
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      handleImageSuccess(res, file, fileList) {
        console.log('res',res)
        console.log('file',file)
        console.log('fileList',fileList)
        this.$emit("addImg", fileList);
      },
      handleRemove(file, fileList) {
      },
      handlePreview(file) {
        console.log(file);
      },
      // 上传图片
      uploadImg(file) {
        // this.$refs.cropper.getCropBlob(data => {
        //   console.log(data)
        //   let formData = new FormData();
        //   formData.append("avatarfile", data);
        //   console.log(formData);
        //   //******************************************************************************************
        //   upload(formData).then(response => {
        //     // uploadAvatar(formData).then(response => {
        //     console.log(response)
        //     //拿到图片地址
        //     this.form.typeUrl = response.imgUrl
        //     console.log(this.form.typeUrl)
        //     if (response.code === 200) {
        //       this.openhead = false;
        //       this.options.img = process.env.VUE_APP_BASE_API + response.imgUrl;
        //       this.msgSuccess("修改成功");
        //     } else {
        //       this.msgError(response.msg);
        //     }
        //     this.$refs.cropper.clearCrop();
        //   }).catch(err=>{
        //     console.log(err)
        //   });
        // });
      },


      /////////////////////////////////////////////////////////////////////////
      //单选上传
      change(event) {
        var _this = this;
        var imgobj = event.target.files[0];

        //if(imgobj.size > 2 * 1000 * 1024){
        // this.$alertShow('您所选择的图片过大，请选择2M以内的图片')
        // return
        //}

        this.uploadQingYun(imgobj)
        event.target.value=''


      },
      //多选上传
      multipleChange(event) {
        var _this = this;
        var imgobjList = event.target.files;
        console.log(imgobjList)
        //if(imgobj.size > 2 * 1000 * 1024){
        // this.$alertShow('您所选择的图片过大，请选择2M以内的图片')
        // return
        //}

        // this.uploadQingYun(imgobj)

        let currNum = 0;
        let fileList = []
        if( imgobjList.length > 0 ){
          uploadFile()

        }

        function uploadFile() {
          let imgObj = imgobjList[currNum]
          if( currNum < imgobjList.length ){
            _this.uploadQingYun(imgObj,(res)=>{
              console.log(res)
              fileList.push(res)
              currNum++
              uploadFile()
            })
          }else{

            let obj ={
              uploadType : _this.multiple,
              fileList : fileList
            }
            if(!!_this.formDataId){
              obj.id = _this.formDataId
            }
            _this.$emit("addImg", obj);
            event.target.value=''
          }

        }

      },

      //青云
      uploadQingYun(imgobj,callBack){
        this.$loadingShow('文件上传中')
        const file = imgobj;
        console.log(file)
        const tmpcnt = file.name.lastIndexOf(".")
        const exname = file.name.substring(tmpcnt + 1)
        const fileNamePre = file.name.substring(0,tmpcnt)
        //file.lastModified +
        let time = new Date().getTime()
        const fileName = fileNamePre +  time +  '.' + exname
        console.log(fileName)
        this.$qingstor.bucket.putObject(fileName, {
          body: file,
        }).then((response) => {
          this.$loadingHide()
          //console.log(response);
          this.$qingstor.bucket.getObject( fileName ).then((response) => {
            //console.log(response)
            // const url = window.URL.createObjectURL(new Blob([response.data]));
            // console.log(url)
            //let url = response.config.url
            //console.log(url)
            let url = `https://${this.$qingstor.qingStorConfig.zone}.qingstor.com/${this.$qingstor.qingStorConfig.bucket}/${fileName}`
            let obj ={
              imgURL : url,
              fileName : file.name,
              uploadType : this.multiple,
            }
            if(!!this.formDataId){
              obj.id = this.formDataId
            }
            if( this.multiple == 'multiple' ){
              callBack(obj)
            }else{
              this.$emit("addImg", obj);
            }


          }).catch((error) => {
            console.log(error);
          });

        }).catch((error) => {
          this.$loadingHide()
          console.log(error);
        });


      },




      //oss
      Upload(file) {

        const that = this
        //判断扩展名
        const tmpcnt = file.name.lastIndexOf(".")
        const exname = file.name.substring(tmpcnt + 1)

        //const names = ['jpg', 'jpeg', 'webp', 'png','bmp']
        //if(names.indexOf(exname)< 0 ){
        //  this.$message.error("不支持的格式!")
        //  return
        //}

        async function multipartUpload () {
          //const fileName = that.name + file.lastModified
          const fileName = ''+file.lastModified +  '.' + exname
          console.log(fileName)
          //定义唯一的文件名，打印出来的uid其实就是时间戳
          //client 是第一步中的 client
          client().multipartUpload(fileName, file,{
            progress:function (p) { //获取进度条的值
              //console.log(p*100)
              let obj ={
                type : 'progress',
                num : Math.floor(p*100)
              }
              if(!!that.formDataId){
                obj.id = that.formDataId
              }
              that.$emit("addImg", obj);
            },
          }).then(
            result => {
              //下面是如果对返回结果再进行处理，根据项目需要
              console.log(result)
              let url = 'http://'+result.bucket+'.'+that.$Base_config.OssSetting.region+ that.$Base_config.OssSetting.preFix + '/' + result.name
              console.log(url)

              let obj ={
                imgURL : url,
              }
              if(!!that.formDataId){
                obj.id = that.formDataId
              }
              that.$emit("addImg", obj);

            }).
          catch(err => {
            console.log("err:",err)
            let obj ={
              type : 'uoLoadErr',
            }
            if(!!that.formDataId){
              obj.id = that.formDataId
            }
            that.$emit("addImg", obj);

          })
        }

        multipartUpload ()


      },





    }
  };
</script>
<style scoped>
  .imgItem {
    float: left;
    position: relative;
    border: 1px dashed #ccc;
  }
  .imgItem > * {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    display: block;
  }
  .imgItem > img {
    width: 40%;
    height: 40%;
    left: 30%;
    top: 30%;
    z-index: 1;
  }
  .imgItem > .delect {
    z-index: 5;
    width: 0.4rem;
    height: 0.4rem;
    right: 0;
    left: auto;
  }
  .imgItem input {
    z-index: 10;
    opacity: 0;
    cursor: pointer;
  }
  .imgItem input[type="file"]{cursor: pointer !important;}

</style>
